package cn.xiaopengstack.domain.agent.service.dispatch.impl;

import cn.xiaopengstack.domain.agent.adapter.repository.IAgentRepository;
import cn.xiaopengstack.domain.agent.model.entity.ExecuteCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentExecuteEnumVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentVo;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientVO;
import cn.xiaopengstack.domain.agent.service.dispatch.IAgentDispatchService;
import cn.xiaopengstack.domain.agent.service.execute.IExecuteStrategy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class AgentDispatchService implements IAgentDispatchService {
    @Resource
    private IAgentRepository repository;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void dispatch(ExecuteCommandEntity requestParameter) throws Exception {
        // 查询Agent的执行类型
        // 此处可以通过使用agentId的前缀来区分是auto还是flow，可以减少一次数据交互
        AiAgentVo aiAgentVo = repository.queryAgentV0ById(requestParameter.getAiAgentId());

        AiAgentExecuteEnumVO aiAgentExecuteEnumVO = AiAgentExecuteEnumVO.valueOf(aiAgentVo.getStrategy());

        // 执行策略
        IExecuteStrategy strategy = applicationContext.getBean(aiAgentExecuteEnumVO.getClazz());

        ResponseBodyEmitter emitter = requestParameter.getEmitter();
        threadPoolExecutor.execute(() -> {
            try {
                strategy.execute(requestParameter, emitter);
            } catch (Exception e) {
                log.error("AutoAgent执行异常：{}", e.getMessage(), e);
                try {
                    emitter.send("执行异常：" + e.getMessage());
                } catch (Exception ex) {
                    log.error("发送异常信息失败：{}", ex.getMessage(), ex);
                }
            } finally {
                try {
                    emitter.complete();
                } catch (Exception e) {
                    log.error("流式输出失败：{}", e.getMessage(), e);
                }
            }
        });
    }

}
